package demo.practice.top100;

import java.util.HashSet;
import java.util.Set;

public class P55 {

    public static void main(String[] args) {
        P55 p55 = new P55();

        p55.canJump(new int[]{2, 3, 1, 1, 4});
    }

    public boolean canJump(int[] nums) {
        if (nums == null || nums.length < 2) {
            return true;
        }
        boolean[] mem = new boolean[nums.length];
        return cj(nums, nums.length - 1, mem);
    }

    public boolean cj(int[] nums, int index, boolean[] mem) {
        if (mem[index]) {
            return true;
        }

        if (index == 0) {
            return true;
        }
        Set<Integer> cjs = new HashSet<>();
        for (int i = index - 1; i >= 0; i--) {
            if (nums[i] + i >= index) {
                cjs.add(i);
            }
        }
        if (cjs.isEmpty()) {
            return false;
        } else {
            for (Integer j : cjs) {
                if (cj(nums, j, mem)) {
                    mem[index] = true;
                    return true;
                }

            }
            return false;
        }
    }
}
